package myoa

import myoa.permission.PermissionSetting

class RoleController {
    //def scaffold = true

    PermissionService permissionService

    def list() {
        [roles: Role.findAll()]
    }

    def review() {
        [permissionSetting: permissionService.reviewPermission()]
    }

    def create() {
        [permissionSetting: permissionService.permissionSetting]
    }

    def save() {
        Role r = new Role(params)
        PermissionSetting ps = permissionService.permissionSetting
        ps.grant(params)
        r.permissions = ps.toPermissions()

        if (r.save()) {
            flash.message = message(code: 'default.save.success')
            redirect(action: 'list')
        } else {
            flash.message = message(code: 'default.save.failed')
            redirect(action: 'create')
        }
    }

    def edit(Long id) {
        Role role = Role.read(id)
        PermissionSetting ps = permissionService.permissionSetting
        ps.grant(role)
        [role: role, permissionSetting: ps]
    }

    def update(Long id) {
        Role r = Role.get(id)
        r.comment = params.comment

        PermissionSetting ps = permissionService.permissionSetting
        ps.grant(params)
        r.permissions = ps.toPermissions()

        if (r.save()) {
            flash.message = message(code: 'default.save.success')
            redirect(action: 'list')
        } else {
            flash.message = message(code: 'default.save.failed')
            render(view: "edit", model: [role: r, permissionSetting: ps])
        }
    }
}
